package com.brian.mongo.controller;

import com.brian.mongo.domain.User;
import com.brian.mongo.exception.UserAlreadyExistException;
import com.brian.mongo.exception.UserNotFoundException;
import com.brian.mongo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-05-16 11:20
 **/

@RestController
@RequestMapping("api/v1/user")
public class UserController {

    private UserService userService;
    private ResponseEntity<?> responseEntity;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/user")
    @ExceptionHandler(UserAlreadyExistException.class)
    public ResponseEntity<?> saveUserToDB(@RequestBody User user) throws UserAlreadyExistException {
        try {
            User user1 = userService.saveUser(user);
            responseEntity = new ResponseEntity<>(user1, HttpStatus.CREATED);
        } catch (UserAlreadyExistException e) {
           throw  new UserAlreadyExistException();
        }catch (Exception e){
            e.printStackTrace();
            responseEntity = new ResponseEntity<>("internet error. Try latter",HttpStatus.EXPECTATION_FAILED);
        }
        return responseEntity;

    }

    @GetMapping("/users")
    public ResponseEntity<?> getAllUsersFromDb() {
        try {
            List<User> allUsers = userService.getAllUsers();
            responseEntity = new ResponseEntity<>(allUsers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            responseEntity = new ResponseEntity<>("internet error. Try latter",HttpStatus.EXPECTATION_FAILED);
        }
        return responseEntity;
    }

    @GetMapping("/getUserByName")
    public ResponseEntity<?> getUserByName(String userName) throws UserNotFoundException {
        return new ResponseEntity<>(userService.getUserByName(userName),HttpStatus.OK);
    }

    @GetMapping("/getUserById")
    public ResponseEntity<?> getUserById(String id) throws UserNotFoundException {
        return new ResponseEntity<>(userService.getUserById(id),HttpStatus.OK);
    }

}
